package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(UserLoginDTO dto) {
        //1.通过HttpClient，构造登录凭证校验请求
            //构造请求参数
        Map<String, String> param = new HashMap<>();
        param.put("appid",weChatProperties.getAppid());
        param.put("secret", weChatProperties.getSecret());
        param.put("js_code",dto.getCode());
        param.put("grant_type","authorization_code");

            //调用HttpClientUtil工具类，发送请求
        String res = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", param);
        log.info("响应结果：{}",res);

        //2.解析响应结果，获取openid
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = (String) jsonObject.get("openid");
        if (openid==null){
            throw new LoginFailedException(MessageConstant.USER_NOT_LOGIN);
        }

        //3.判断是否为新用户，根据openid查询数据库
        User user= userMapper.selectByOpenid(openid);
        //4.如果为新用户，插入数据
        if (user==null){
            user=User.builder()
                    .openid(openid)
                    .name(openid.substring(0,5))
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        //否则，返回user对象数据
        return user;
    }
}
